package com.cloudinnov.test;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudinnov.mapper.CarLineData;
import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

public class MongoTest4 {

	  static MongoTemplate mongoTemplate;
		 
	    @Before
	    public void testBefore() {
	        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-mongodb.xml");
	        mongoTemplate = (MongoTemplate) context.getBean("mongoTemplate");
	    }

	    @Test
	    public void testAddUser() throws ParseException {
	    	
	    	//方案1：
	    	 //String groupStr = "{\"$group\":{_id:{equipmentCode:\"$equipmentCode\",data:{\"$sum\":\"$data.lineFlow\"},year: { \"$year\": \"$utcTime\" } }}}";
	    	 String groupStr = "{\"$group\":{_id:{equipmentCode:\"$equipmentCode\",data:{\"$data.lineFlow\":{\"$slice\":3}},year: { \"$year\": \"$utcTime\" } }}}";
		     BasicDBObject group = JSON.parseObject(groupStr, BasicDBObject.class);
		     AggregationOutput output = mongoTemplate.getCollection("carDetectorData").aggregate(group);  
		     List<Map<String, Object>> data = new ArrayList<>();
		     Integer chengdu=0;
			 Integer chongqing=0;
			 for (DBObject object:output.results()) {
				 
			 	 
				DBObject dbObject = (DBObject) object.get("_id");
			 	 
			 	Object dataObject = dbObject.get("data");
			 	//System.err.println(dataObject);
			 	List<CarLineData> carDataList = JSON.parseArray(dataObject.toString(), CarLineData.class);
			 	//System.err.println(carDataList);
			 	 
//			 	for (int i = 0; i < carDataList.size(); i++) {
//					if(carDataList.get(i).getLineId()<=3){
//						chengdu=chengdu+carDataList.get(i).getLineFlow();
//					}else{
//						chongqing=chongqing+carDataList.get(i).getLineFlow();
//					}
//				}
//
//			 }
//			 //输出各个重庆 成都 的车流量总和
//			 System.err.println("chengdu:"+chengdu);
//			 System.err.println("chongqing:"+chongqing);
			 }
	    }
	
}
